# -*- coding: UTF-8 -*- 
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.db import transaction
from dawn.accounts.forms import RegForm, EditPictureForm
from dawn.accounts.models import UserProfile
from dawn.friends.models import FriendGroup
import datetime

@transaction.commit_on_success
def reg(request):
    if request.method == 'POST':
        form = RegForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data;
            user = User.objects.create_user(cleaned_data['email'], cleaned_data['email'], cleaned_data['password'])
            user.first_name = cleaned_data['first_name']
            user.last_name = cleaned_data['last_name']
            user.save()

            profile = UserProfile();
            profile.user = user
            profile.gender = cleaned_data['gender']
            profile.birthday = cleaned_data['birthday']
            profile.logo = '/site_media/img/profile.gif'

            friend_group = FriendGroup(user=user, name=u'所有朋友', is_default=True)
            friend_group.save()
            
            return HttpResponseRedirect('/accounts/waitactivation/')
    else:
        form = RegForm()
    return render_to_response('accounts/reg.html', {'form': form})

def login(request):
    fail = False;
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            return HttpResponseRedirect('/home/')
        else:
            fail = True;
    return render_to_response("accounts/login.html", {'fail': fail})

def logout(request):
    '''退出并重新定位到/页面'''
    auth.logout(request)
    return HttpResponseRedirect('/')

@login_required
def edit_picture(request):
    if request.method == 'POST':
        form = EditPictureForm(request.POST, request.FILES)
        if form.is_valid():
            f = request.FILES['picture']
            import os
            ext = os.path.splitext(f.name)[1]
            
            virtual_save_path = '/upload/%s/%s%s' % (request.user.id, request.user.id, ext)
            pyl_save_path = '.' + virtual_save_path
            
            pyl_save_dir = os.path.dirname(pyl_save_path)
            if not os.path.exists(pyl_save_dir):
                os.mkdir(pyl_save_dir)
            
            #保存上传的图片到磁盘
            destination = open(pyl_save_path, 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
            
            from dawn.utils import make_thumb
            #将原图缩略
            make_thumb(pyl_save_path, (200, 150, 50))
            
            #删除原图
            os.remove(pyl_save_path)
            
            profile = request.user.get_profile()
            #默认logo字段存储最小尺寸的图片
            profile.logo = '/upload/%s/%s_50x50.jpg' % (request.user.id, request.user.id)
            profile.save()
            return HttpResponseRedirect('/profile/%s/' % request.user.id)
    else:
        form = EditPictureForm()
    return render_to_response('accounts/edit_picture.html', {'form': form}, context_instance=RequestContext(request))
    
